﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using ChatServerApp.Classes;
using ChatServerApp.Tools;

namespace ChatServerApp.GUI
{
    public partial class ServerApp : Form
    {
        public static DelegateLogEntry dle;
        public delegate void DelegateLogEntry(String value);

        public ServerApp()
        {
            InitializeComponent();
            this.Text = "Server.APP";
            ActiveComponents.FillUserList();
            ServerClass.OnSendMessageHandler += new ServerClass.SendMessageEventHandler(server_OnSendMessageHandler);
            bgWorkerServer.RunWorkerAsync();
        }

        private void bgWorkerServer_DoWork(object sender, DoWorkEventArgs e)
        {
            /*
            List<ClientObject> clients = null;

            if (File.Exists("logins.txt"))
                clients = readInClientObjects();
            else
            {
                clients = new List<ClientObject> { new ClientObject(0, "DUMMY", "DUMMY", String.Empty, 0, String.Empty, false) };
            }
            */
            ServerClass server = new ServerClass();
        }

        /*
        private List<ClientObject> readInClientObjects()
        {
            String[] tempClientObjects = File.ReadAllLines("logins.txt");
            List<ClientObject> coList = new List<ClientObject>();
            int counter = 0;

            foreach (String element in tempClientObjects)
            {
                String[] tempObject = element.ToAsciiString(";");
                coList.Add(new ClientObject(counter, tempObject[0], tempObject[1], String.Empty, 0, tempObject[2], false));
                counter++;
            }
            return coList;
        }
        */
        
        public void addLogEntry(String text)
        {
            DateTime dt = DateTime.Now;

            if (!InvokeRequired)
            {
                richTextBox1.AppendText(dt.Year + "/" + dt.Month + "/" + dt.Day + " " + dt.ToShortTimeString() + ": " + text + Tools.Tools.NL);
            }
            else
            {
                Invoke(new DelegateLogEntry(addLogEntry), new object[] { text });
            }
        }

        void server_OnSendMessageHandler(object sender, MessageEventArgs e)
        {
            this.addLogEntry(e.Message);
        }
    }
}
